IoT based Energy Consumption meter
Components:
ï‚§ Esp8266 nodeMCU
ï‚§ ZMPT101B AC Voltage Sensor
ï‚§ SCT013 Current Sensor
ï‚§ 10K ohm Resistor
 10 micro–F Capacitor
Circuit Diagram:
Hardware Setup:
Live Data into Google Sheets:
Real time power consumption of a 5V led bulb.
Arduino code:
// EmonLibrary examples openenergymonitor.org, Licence GNU GPL V3
#include "EmonLib.h" // Include Emon Library
EnergyMonitor emon; // Create an instance
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#define ON_Board_LED 2 //--> Defining an On Board LED, used for indicators when
the process of connecting to a wifi router
const char* ssid = "********"; //--> Your wifi name or SSID.
const char* password = "********"; //--> Your wifi password.
//----------------------------------------Host & httpsPort
const char* host = "script.google.com";
const int httpsPort = 443;
//----------------------------------------
WiFiClientSecure client; //--> Create a WiFiClientSecure object.
String GAS_ID = "AKfycbzaloNi2OtJywzYhBU2pzdkh-
JRDE0w_wkgmDVBZLKQLQ6sSLh9zN60APseuqLew_2AWw"; //--> spreadsheet script ID
// Variables for energy calculation
float kWh = 0.0;
unsigned long lastMillis = millis();
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password); //--> Connect to your WiFi router
Serial.println("");
pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on
the process of connecting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is
connected to the wifi router.
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
client.setInsecure();
emon.voltage(D0, 137.57, 1.7); // Voltage: input pin, calibration, phase_shift
emon.current(D1, 0.0941); // Current: input pin, calibration.
}
void loop()
{
emon.calcVI(20, 400); // Calculate all. No.of half wavelengths (crossings),
time-out
//Calculate energy consumed in kWh
unsigned long currentMillis = millis();
kWh += emon.apparentPower * (currentMillis - lastMillis) / 3600000000.0;
lastMillis = currentMillis;
// Print data to Serial for debugging
float v = emon.Vrms;
float i = emon.Irms;
float p = emon.apparentPower;
Serial.printf("Vrms: %.2fV\tIrms: %.4fA\tPower: %.4fW\tkWh: %.5fkWh\n",
v, i, p, kWh);
sendData(v, i, p, kWh);
delay(55200);
}
// Subroutine for sending data to Google Sheets
void sendData(float v, float i, float p, float kwh) {
Serial.println("==========");
Serial.print("connecting to ");
Serial.println(host);
//----------------------------------------Connect to Google host
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
//----------------------------------------
//----------------------------------------Processing data and sending data
String string_v = String(v, DEC);
String string_i = String(i, DEC);
String string_p = String(p, DEC);
String string_kwh = String(kwh, DEC);
String url = "/macros/s/" + GAS_ID + "/exec?voltage=" + string_v + "&current="
+ string_i + "&power=" + string_p + "&kwh=" + string_kwh;
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
//----------------------------------------
//----------------------------------------Checking whether the data was sent
successfully or not
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.print("reply was : ");
Serial.println(line);
Serial.println("closing connection");
Serial.println("==========");
Serial.println();
//----------------------------------------
}
Google Apps Script code:
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '12GAxTVI8JvMG_B71rtJl_eSdNZhgzzD35s_SWKSugIo'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Asia/Dhaka", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'voltage':
rowData[2] = value; // Voltage in column C
result = 'Voltage Written on column C';
break;
case 'current':
rowData[3] = value; // Current in column D
result += ' ,Current Written on column D';
break;
case 'power':
rowData[4] = value; // Power in column E
result += ' ,Power Written on column E';
break;
case 'kwh':
rowData[5] = value; // kWh in column F
result += ' ,kWh Written on column F';
break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
Dashboard Preview:
Real Time data from google sheet to our website.